// pages/StSwitchCity/StSwitchCity.js
import { LETTERS, HOT_CITY_LIST } from '../../cityselector/data/citydata'
import { commonMessage } from '../../cityselector/data/commonMessageZhCn'
import { AutoPredictor } from '../../cityselector/config/autoPredictor'
import utils from '../../cityselector/config/utils'
const {
  isNotEmpty,
  safeGet,
  getCityListSortedByInitialLetter,
  getLocationUrl,
  getCountyListUrl,
  getIndexUrl,
  onFail,
} = utils;
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        hidden: true,
        list:['-','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','W','X','Y','Z'],
        listCur:'A',
        searchValue:'',
        showKey:{
            'A':true,'B':true,'C':true,'D':true,'E':true,'F':true,'G':true,'H':true,'J':true,'K':true,'L':true,'M':true,'N':true,'P':true,'Q':true,'R':true,'S':true,'T':true,'W':true,'X':true,'Y':true,'Z':true
        },
        cityList:{},
        city:'',
        currentCityCode:'',
        auto: true, // 自动手动定位开关
    },
    _blockClick(e){
        let city = e.currentTarget.dataset.city;
        app.globalData.defaultCity = city
        app.globalData.defaultCounty = ''
        this.BackPage();
    },
    bindtapInput(e){
        this.setData({
            searchValue :e.detail.value
        })
    },     
    // 内部过滤
    brandListSearch(){
        app.showLoading("正在搜索");
        let cityList = app.deepCopy(this.data.cityList);
        let showKey = app.deepCopy(this.data.showKey);
        let searchValue = this.data.searchValue;
        for (const key in cityList) {
            if (Object.hasOwnProperty.call(cityList, key)) {
                const element = cityList[key];
                let showTheKey = false;
                element.forEach(element => {
                    if("" == searchValue){
                        element['show'] = 1;
                        showTheKey = true;
                    }else{
                        if(element.city.indexOf(searchValue) != -1){
                            element['show'] = 1;
                            showTheKey = true;
                        }else{
                            element['show'] = 0;
                        }
                    }
                });
                showKey[key] = showTheKey;
            }
        };
        wx.hideLoading();
        this.setData({
            cityList: cityList,
            showKey: showKey
        })
    },
    setCur(e) {
        this.setData({
            hidden: true,
            listCur: this.data.listCur
        })
    },
    //滑动选择Item
    tMove(e) {
        let y = e.touches[0].clientY,
        offsettop = this.data.boxTop,
        that = this;
        //判断选择区域,只有在选择区才会生效
        if (y > offsettop) {
        let num = parseInt((y - offsettop) / 20);
        this.setData({
            listCur: that.data.list[num]
        })
        };
    },
    //触发全部开始选择
    tStart() {
        this.setData({
        hidden: false
        })
    },
    //触发结束选择
    tEnd() {
        this.setData({
        hidden: true,
        listCurID: this.data.listCur
        })
    },
    indexSelect(e) {
        let that = this;
        let barHeight = this.data.barHeight;
        let list = this.data.list;
        let scrollY = Math.ceil(list.length * e.detail.y / barHeight);
        for (let i = 0; i < list.length; i++) {
        if (scrollY < i + 1) {
            that.setData({
            listCur: list[i],
            movableY: i * 20
            })
            return false
        }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 定位
        this.getLocation();
        const cityListSortedByInitialLetter = getCityListSortedByInitialLetter();
        let cityList = {};
        cityListSortedByInitialLetter.forEach(item =>{
            cityList[item.initial] = item.cityInfo;
        })
        this.setData({
            'cityList': cityList
        })
    },
    getLocation: function () {
        console.log(commonMessage['location.city.getting'])
    
        this.setData({ county: '' })
        wx.getLocation({
          type: 'wgs84',
          success: res => this.getLocationFromGeoCoord(res),
          fail: onFail(commonMessage['location.city.fail']),
        })
    },
    getLocationFromGeoCoord: function (geoCoord) {
        const { latitude, longitude } = geoCoord
        wx.request({
            url: getLocationUrl(latitude, longitude),
            success: location => this.setCityCounty(location)
        })
    },
    setCityCounty: function (location) {
        const { city, adcode, district } = safeGet(['data', 'result', 'ad_info'], location)
        if (this.data.auto) { // 如果开始手动选择，以手动为准
            this.setData({
            city,
            currentCityCode: adcode,
            // county: district
            })
            // app.globalData.defaultCity = city
        }
    },
    onReady: function(){
        let that = this;
        let query = wx.createSelectorQuery();
        query.select('.indexBar-box').boundingClientRect(function(res) {
            that.setData({
                boxTop: res.top
            })
        }).exec();
        
        query.select('.indexes').boundingClientRect(function(res) {
            that.setData({
                barTop: res.top
            })
        }).exec()
    },
    // 返回上一页

    BackPage() {
        var that = this;
        wx.navigateBack({
          delta: 1,
          fail: function(){
            that.toHome();
          }
        });
    },
    toHome(){
        wx.reLaunch({
            url: '/pages/home/home',
        })
    }

})